package com.chujian.system.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chujian.framework.core.base.BaseServiceImpl;
import com.chujian.sys.entity.SysRole;
import com.chujian.sys.entity.SysRoleMenu;
import com.chujian.system.sys.mapper.SysRoleMenuMapper;
import com.chujian.system.sys.service.SysRoleMenuService;
import com.chujian.system.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 角色功能表 服务实现类
 *
 * @author chujian
 * @since 2021-08-03
 */
@Service
@Slf4j
public class SysRoleMenuServiceImpl extends BaseServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Autowired
    private SysRoleService roleService;

    @Override
    public List<SysRoleMenu> listRoleMenu(List<Long> roleIds, boolean full) {
        if (!full) {
            return this.list(
                    new LambdaQueryWrapper<SysRoleMenu>()
                            .in(SysRoleMenu::getRoleId, roleIds)
            );
        }
        String roleIdStrs = CollUtil.join(roleIds, ", ");
        QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<SysRoleMenu>().in("rm.role_id", roleIds);
        return baseMapper.listRoleMenu(roleIdStrs);
    }

    @Override
    @Transactional
    public void saveRoleMenu(Long roleId, List<Long> menuIds) {
        if (null == menuIds) {
            menuIds = new ArrayList<>();
        }
        roleService.forUpdate(roleId, SysRole.class);
        List<Long> existIds = this.listRoleMenu(CollUtil.newArrayList(roleId), false)
                .stream()
                .map(SysRoleMenu::getMenuId)
                .collect(Collectors.toList());

        // existIds - menuIds delete
        ArrayList<Long> list = new ArrayList<>(existIds);
        list.removeAll(menuIds);
        if (CollUtil.isNotEmpty(list)) {
            this.remove(
                    new LambdaQueryWrapper<SysRoleMenu>()
                            .eq(SysRoleMenu::getRoleId, roleId)
                            .in(SysRoleMenu::getMenuId, list)
            );
        }

        // menuIds - existIds insert
        menuIds.removeAll(existIds);
        if (CollUtil.isNotEmpty(menuIds)) {
            for (Long menuId : menuIds) {
                SysRoleMenu roleMenu = new SysRoleMenu().setMenuId(menuId).setRoleId(roleId);
                this.save(roleMenu);
            }
        }
    }


}
